<template>
  <switch-component></switch-component>
</template>

<script setup lang="tsx">
import { FormItem, Switch } from 'tdesign-vue-next';
import { inject, onMounted, Ref } from 'vue';

import { TDFormItemType } from '../type.d';

const {
  componentAttribute = {},
  formItemAttribute = {},
  name,
} = defineProps<{
  componentAttribute: TDSwitchType;
  name: string;
  formItemAttribute: TDFormItemType;
}>();

type TDSwitchType = InstanceType<typeof Switch>['$props'];

const defaultComponentAttribute: TDSwitchType = {};
const defaultFormItemAttribute: TDFormItemType = {
  name,
  rules: [
    {
      required: true,
      message: `${formItemAttribute.label || '此项'}必填`,
      trigger: 'change',
    },
  ],
};

const modelValue: Ref = inject('dynamicFormData');

onMounted(() => {
  if (modelValue.value[name] === undefined || modelValue.value[name] === null) {
    throw new Error('switch组件必须绑定一个动态数据');
  }
});

const SwitchComponent = (
  <FormItem {...defaultFormItemAttribute} {...formItemAttribute}>
    <Switch v-model={modelValue.value[name]} {...defaultComponentAttribute} {...componentAttribute} />
  </FormItem>
);
</script>

<style scoped></style>
